<template>
  <div class="login">
    <u-form :model="form" ref="uForm" :error-type="errorType" label-width="120rpx" label-align="center">
      <u-form-item prop="email" label="邮箱" 
        ><u-input v-model="form.email"
      /></u-form-item>
      <u-form-item prop="passwd" label="密码"
        ><u-input v-model="form.passwd"
      /></u-form-item>
    </u-form>
    <div class="btn_foot">
      <u-button type="success" @click="loginFn">登录</u-button>
      <u-button @click="goReg">注册</u-button>
    </div>
    <u-toast ref="uToast" />
  </div>
</template>
<script>
export default {
  data() {
    return {
      errorType: ['toast'],
      form: {
        email: "",
        passwd: ""
      },
      rules: {
        email: [
          {
            required: true,
            message: "邮箱不能为空",
            trigger: "blur"
          }
        ],
        passwd: [
          {
            required: true,
            message: "密码不能为空",
            trigger: "blur"
          }
        ]
      }
    };
  },
  onReady() {
    this.$refs.uForm.setRules(this.rules);
  },
  methods: {
    goReg() {
      uni.navigateTo({
        url: "../reg/index"
      });
    },
    loginFn() {
      this.$refs["uForm"].validate(valid => {
        if (valid) {
          let that = this;
          uni.request({
            url: "http://39.106.224.223:8088/ac/api/login",
            header: {
              "content-type": "application/x-www-form-urlencoded"
            },
            method: "POST",
            data: {
              email: that.form.email,
              passwd: that.form.passwd
            },
            success: res => {
              if (res.data.code == 200) {
                let obj = {
                  account:res.data.data.account,
                  userInfo:res.data.data.exten.userInfo
                }
                this.$store.dispatch("userActions", obj);
                this.$store.dispatch("tokenActions", res.data.data.token);
                // wx.setStorageSync("user", obj);
                // wx.setStorageSync("token", res.data.data.token);
                this.$refs.uToast.show({
                  title: "登录成功",
                  type: "success"
                });
                uni.reLaunch({
                   url: '../index/index'
                });
              } else {
                this.$refs.uToast.show({
                  title: "登录失败",
                  type: "error"
                });
              }
            },
            fail(er) {
              console.log(er);
            }
          });
        }
      });
    }
  }
};
</script>
<style lang="scss">
.login {
  width: 100%;
  height: 100%;
  .btn_foot {
    padding: 20rpx 10rpx;
    button {
      margin: 20rpx 0;
    }
  }
}
</style>